package com.wh.custom.controller;

import com.wh.basic.vo.AjaxResult;
import com.wh.custom.dto.CustomAddValidationDto;
import com.wh.custom.dto.CustomSearchDto;
import com.wh.custom.pojo.Allocation;
import com.wh.custom.service.ICustomMycustomService;
import com.wh.custom.pojo.CustomMycustom;
import com.wh.custom.dto.CustomMycustomQueryDto;
import com.wh.custom.vo.*;
import com.wh.order.vo.OrderExportVo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.date.DateUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;


import java.sql.Date;
import java.util.List;
import java.util.Map;

/**
 * 后端接口类；
 */
@RestController
@RequestMapping("/customMycustom")
public class CustomMycustomController {

    @Autowired
    public ICustomMycustomService customMycustomService;

    @PostMapping("getCustomDataCount")
    public AjaxResult getCustomDataCount(String type){
        Map<String, Object> datas = customMycustomService.getCustomDataCount(type);
        return AjaxResult.me().setSuccess(true).setResultObj(datas);
    }
    /**
     * 接口：添加或修改
     *
     * @param customMycustom 传递的实体
     * @return AjaxResult 响应给前端
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody CustomMycustom customMycustom) {
        if (customMycustom.getId() != null) {
            customMycustomService.updateCustomer(customMycustom);
//        } else {
//            customMycustomService.addCustomer(customMycustom);
        }
        return new AjaxResult();

    }
    @PutMapping("/addcustomer")
    public AjaxResult addcustomer( @RequestParam Long LoginId,@RequestBody  CustomMycustom customMycustom){
        customMycustomService.addCustomer(customMycustom,LoginId);
        return new AjaxResult();
    }

    /**
     * 我的客户添加
     * 非公海客户
     *
     * @param customMycustom
     * @return
     */
    @PutMapping("/AddMycustom")
    public AjaxResult AddMycustom(@RequestBody CustomMycustom customMycustom) {
        customMycustomService.AddMycustom(customMycustom);
        return new AjaxResult();
    }

    //多条件搜索----
    @PostMapping("/getCustomerList")
    public IPage<CustomMycustom> aaaa(@RequestBody CustomSearchDto customSearchDto) {
        return customMycustomService.getAaaa(customSearchDto);
    }

    /**
     * 公海客户多条件查询
     *
     * @param customSearchDto
     * @return
     */
    @PostMapping("/getHighSeas")
    public IPage<CustomMycustom> getHighSeas(@RequestBody CustomSearchDto customSearchDto) {
        return customMycustomService.getHighSeas(customSearchDto);
    }

    /**
     * 我的客户多条件查询
     *
     * @param customSearchDto
     * @return
     */
    @PostMapping("/getMyCustom")
    public IPage<CustomMycustom> getMyCustom(@RequestBody CustomSearchDto customSearchDto) {
        return customMycustomService.getMyCustom(customSearchDto);
    }

    /**
     * 接口：删除
     *
     * @param id
     * @return AjaxResult 响应给前端
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        customMycustomService.removeById(id);
        return new AjaxResult();
    }

    /**
     * 接口：批量删除
     *
     * @param ids
     * @return AjaxResult 响应给前端
     */
    @PatchMapping
    public AjaxResult patchDel(@RequestBody List<Long> ids) {
        customMycustomService.removeByIds(ids);
        return new AjaxResult();
    }

    /**
     * 接口：查询单个对象
     *
     * @param id
     */
    @GetMapping("/{id}")
    public CustomMycustom findOne(@PathVariable("id") Long id) {
        return customMycustomService.getById(id);
    }

    /**
     * 选中字段导出
     */
//    @PostMapping(value = "/export")
//    public void export(HttpServletResponse response, @RequestBody CustomExportPoiDto poiDto) {
//        List<CustomExportDto> exportDtos = poiDto.getExportDto();
//        String id = poiDto.getId();
//        String[] idArr = null;
//        if(StringUtils.hasLength(id)){
//            idArr = id.split(",");
//        }
//        CustomExport customExport = customMycustomService.exportSSL(exportDtos,idArr);
//        if (customExport == null) {
//            return;
//        }
//        String[] labels = customExport.getLabels();
//        String[] props = customExport.getProps();
//        List<CustomExportVo> exportVos = customExport.getExportVos();
//        Workbook workbook = null;
//        // 创建一个新的Workbook
//        try {
//            workbook = new XSSFWorkbook();
//
//            Font headerFont = workbook.createFont();
//            headerFont.setBold(true);
//            // 创建一个Sheet，代表一个工作表
//            Sheet sheet = workbook.createSheet("sheet1");
//            CellStyle headerStyle = workbook.createCellStyle();
//            headerStyle.setFont(headerFont);
//            headerStyle.setAlignment (HorizontalAlignment.CENTER);
//
//            // 创建表头（字段）
//            // 在第一行写入表头
//            Row headerRow = sheet.createRow(0);
//            for (int i = 0; i < labels.length; i++) {
//                if (StringUtils.hasLength(labels[i])) {
//                    Cell cell = headerRow.createCell(i);
//                    cell.setCellValue(labels[i]);
//                    cell.setCellStyle(headerStyle);
//                }
//            }
//
//            for (int i = 0; i < exportVos.size(); i++) {
//                Row row = sheet.createRow(i+1);
//                for (int j = 0; j < props.length; j++) {
//                    if (StringUtils.hasLength(props[j])) {
//                        Cell cell = row.createCell(j);
//                       if ("createTime".equals(props[j]) || "lastOperationTime".equals(props[j])) {
//                            String date = DateUtil.format((Date) invokeGetMethod(CustomExportVo.class, props[j], exportVos.get(i)), "yyyy-MM-dd HH:mm:ss");
//                            cell.setCellValue(date);
//                        } else {
//                            cell.setCellValue((String) invokeGetMethod(CustomExportVo.class, props[j], exportVos.get(i)));
//                        }
//                    }
//                }
//            }
//            String fileName = "orderInfo.xlsx";
//            //把生成的excel文件下载到客户端
//            response.setContentType("application/vnd.openxmlformats-officeedocument.sheet;charset=utf-8");
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            ServletOutputStream os = response.getOutputStream();
//            workbook.write(os);
//            os.flush();
//            os.close();
//            workbook.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//        }
//    }

    /**
     * 客户信息导出esaypoi版
     * @param response
     * @param poiDto
     */
 @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestBody CustomExportPoiDto poiDto) {

    }

    /**
     *客户记录，根据订单编号，查找此项订单信息
     */
    @GetMapping("/getOrderMessageByOrderSn")
    public List<CustomRecordVo> getOrderMessageByOrderSn(String orderSn){
        List<CustomRecordVo> customRecordVos = customMycustomService.getOrderMessageByOrderSn(orderSn);
        return customRecordVos;
    }
    /**
     * 拼接属性，调用目标Class的get方法
     *
     * @param c         属性所属实体类
     * @param fieldName 需要调用的属性名
     * @param obj       实体类实例
     * @return 返回get方法结果
     */
    public static Object invokeGetMethod(Class<?> c, String fieldName, Object obj) {
        try {
            // 确保字段名不是空的
            if (fieldName == null || fieldName.isEmpty()) {
                throw new IllegalArgumentException("Field name cannot be null or empty");
            }

            // 创建 getter 方法名
            String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);

            // 查找方法，指定参数类型为空（对于 getter 方法）
            Method method = c.getMethod(methodName, new Class<?>[]{});

            // 确保 obj 是 c 的一个实例
            if (!c.isInstance(obj)) {
                throw new IllegalArgumentException("Object is not an instance of the specified class");
            }

            // 调用方法并返回结果
            return method.invoke(obj);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // 处理或重新抛出异常（这里只是简单地将其包装为 RuntimeException）
            throw new RuntimeException(e);
        }
    }
    /**
     * 导出模板
     *
     * @param response
     */
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        customMycustomService.exportTemplate(response);
    }

    /**
     * 我的客户数据导出
     *
     * @param response
     */
    @GetMapping("/mycustomerexport/{LoginId}")
    public void mycustomerexport(@PathVariable("LoginId") Long LoginId, HttpServletResponse response) {
        customMycustomService.mycustomerexport(LoginId, response);
    }

    /**
     * 接口：查询所有
     *
     * @return
     */
    @GetMapping
    public List<CustomMycustom> findAll() {
        return customMycustomService.list();
    }

    @GetMapping("/num")
    public Integer all() {
        return customMycustomService.allNum();
    }

    //数据导入
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestPart("file") MultipartFile file) {
        try {
            customMycustomService.importExcel(file);
            return AjaxResult.me().setMessage("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("导入失败：" + e.getMessage());
        }
    }

    /**
     * 接口：分页查询或高级查询
     *
     * @param customMycustomQueryDto 查询对象
     * @return IPage<CustomMycustom> 分页对象
     */
    @PostMapping
    public IPage<CustomMycustom> findByPage(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.findByPage(customMycustomQueryDto);
    }

    /**
     * 查询公海客户
     *
     * @param customMycustomQueryDto
     * @return
     */
    @PostMapping("/highSeas")
    public IPage<CustomMycustom> findhighSeas(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.findhighSeas(customMycustomQueryDto);
    }

    /**
     * 查询我的客户
     *
     * @param customMycustomQueryDto
     * @return
     */
    @PostMapping("/mycustomer")
    public IPage<CustomMycustom> mycustomer(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.mycustomer(customMycustomQueryDto);
    }

    /**
     * 分类搜索
     *
     * @param customMycustomQueryDto
     * @return
     */
    @PostMapping("/sort")
    public IPage<CustomMycustom> sort(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.sort(customMycustomQueryDto);
    }

    /**
     * 公海客户分类搜索
     *
     * @param customMycustomQueryDto
     * @return
     */
    @PostMapping("/HighSeasSort")
    public IPage<CustomMycustom> HighSeasSort(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.HighSeasSort(customMycustomQueryDto);
    }

    @PostMapping("/all")
    public IPage<CustomMycustom> all(@RequestBody CustomMycustomQueryDto customMycustomQueryDto) {
        return customMycustomService.all(customMycustomQueryDto);
    }

    /*分配客户
     */
    @PutMapping("allocation")
    public AjaxResult allocation(@RequestBody Allocation allocation) {

        customMycustomService.allocation(allocation);
        return new AjaxResult();
    }

    /*
    收回公海
     */
    @PutMapping("/recovery")
    public AjaxResult recovery(@RequestBody List<Long> ids) {
        customMycustomService.recovery(ids);
        return new AjaxResult();
    }

    @PostMapping("/checkCustomer")
    public AjaxResult checkCustomer(@RequestBody Map<String, String> requestBody) {
        // 从请求中获取手机号
        String phoneNumber = requestBody.get("phoneNumber");
        // 查询数据库中是否存在对应的客户
        Long customerId = customMycustomService.checkCustomer(phoneNumber);
        if (customerId != null) {
            return AjaxResult.me().setResultObj(customerId);
        } else {
            // 如果不存在客户，直接返回AjaxResult
            return AjaxResult.me();
        }
    }


    @PutMapping("/orderToCustomer")
    public AjaxResult orderToCustomer(@RequestBody CustomMycustom customMycustom) {
        Integer customerId = customMycustomService.addOrderCustomer(customMycustom);
        return AjaxResult.me().setResultObj(customerId);
    }

    /**
     * 查询手机号和公司名称是否重复
     * @param customAddValidationDto
     * @return
     */
    @PutMapping("/phoneValidation")
    public Map<String, Object> phoneValidation(@RequestBody CustomAddValidationDto customAddValidationDto){
        Map<String, Object> boo = customMycustomService.phoneValidation(customAddValidationDto);
        return boo;
    }
    @PostMapping("/top")
    public AjaxResult top(@RequestBody Map<String, Integer> params) {
        Integer id = params.get("id");
        customMycustomService.top(id);
        return new AjaxResult(); // 返回响应
    }

    @PostMapping("/down")
    public AjaxResult down(@RequestBody Map<String, Integer> params) {
        Integer id = params.get("id");
        customMycustomService.down(id);
        return new AjaxResult(); // 返回响应
    }
//    个人数据查看是否置顶
    @PostMapping("/personalTop")
    public AjaxResult personalTop(@RequestBody Map<String, Integer> params) {
        Integer id = params.get("id");
        customMycustomService.personalTop(id);
        return new AjaxResult(); // 返回响应
    }

    @PostMapping("/personalDown")
    public AjaxResult personalDown(@RequestBody Map<String, Integer> params) {
        Integer id = params.get("id");
        customMycustomService.personalDown(id);
        return new AjaxResult(); // 返回响应
    }
}
